package com.koalac.ironman.util;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;

import com.koalac.ironman.net.MyRequest;
import com.koalac.ironman.widget.LoadingDialog;

/**
 * 代码写得比较乱,待调整@badcode
 * @author admin  2014年10月30日
 */
public class MyHandler extends Handler {

	/**
	 * 是否拒绝接收消息
	 */
	private boolean rejectMessage = false;
	private LoadingDialog p;
	private Timer timeoutTimer;

	public MyHandler(Looper looper, LoadingDialog p) {
		super(looper);
		this.p = p;
		/**
		 * 计时器,一超时取消所有的请求
		 */
		timeoutTimer = new Timer(true);
		timeoutTimer.schedule(new TimerTask() {

			@Override
			public void run() {
				Message msg = obtainMessage();
				msg.what = KeyUtil.TIME_OUT_CODE;
				MyHandler.this.sendMessage(msg);
			}
		}, MyRequest.getHttpClient().getTimeout());
	}

	@Override
	public void dispatchMessage(Message msg) {
		if (rejectMessage) {
			timeoutTimer.cancel();
			if (p != null) {
				p.cancel();
			}
			return;
		}
		if (msg.what == KeyUtil.TIME_OUT_CODE) {
			MyRequest.getHttpClient().cancelAllRequests(true);
			if (p != null && p.isShowing()) {
				p.cancel();
				Toast.makeText(p.getContext(), "网络状况欠佳,请稍后再试!",
						Toast.LENGTH_SHORT).show();
			}
			rejectMessage = true;
			timeoutTimer.cancel();
		} else if (msg.what == KeyUtil.REQUEST_SUCCESS_CODE
				|| msg.what == KeyUtil.REQUEST_FAIL_CODE) {
			rejectMessage = true;
			timeoutTimer.cancel();
			if (p != null) {
				p.cancel();
			}
			if (msg.what == KeyUtil.REQUEST_FAIL_CODE && p != null) {
				Toast.makeText(p.getContext(), "网络状况欠佳,请稍后再试!",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	public void setRejectMessage(boolean rejectMessage) {
		this.rejectMessage = rejectMessage;
	}

}
